package com.chengweiyi.security.filter;

import com.chengweiyi.security.security.TokenManager;
import io.jsonwebtoken.Claims;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.expression.SecurityExpressionHandler;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @Author xiao hu die
 * @Date 2022/5/13 17:12
 * @Version 1.0
 */
public class TokenAuthFilter extends BasicAuthenticationFilter {
    private TokenManager tokenManager;
    private RedisTemplate redisTemplate;

    public TokenAuthFilter(AuthenticationManager authenticationManager, TokenManager tokenManager, RedisTemplate redisTemplate) {
        super(authenticationManager);
        this.tokenManager = tokenManager;
        this.redisTemplate = redisTemplate;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
       /**获取认证成功用户权限信息*/
       UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = getAuthentication(request);
       /**如果有权限信息，放到权限上下文中*/
       if (usernamePasswordAuthenticationToken!=null){
           SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
       }
       chain.doFilter(request,response);
    }

    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
           /**从header获取token*/
        String token = request.getHeader("token");
         if (token !=null){
             Claims userInfoFromToken = tokenManager.getUserInfoFromToken(token);
             /**得到用户名*/
             String username = userInfoFromToken.getSubject();
             List<String> list = (List<String>) redisTemplate.opsForValue().get(username);
             Collection<GrantedAuthority> authorities = new ArrayList<>();
             for (String s : list) {
                 SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(s);
                 authorities.add(simpleGrantedAuthority);
             }
             return new UsernamePasswordAuthenticationToken(username,token,authorities);
         }
         return null;
    }
}
